Page({
  data: {
    score: 0,
    targetScore: 50,
    numbers: [],
    gameStatus: '', // 'win' 或 'lose'
    message: '',
    hintIndex: -1
  },

  onLoad() {
    this.initGame()
  },

  // 初始化游戏
  initGame() {
    this.setData({
      score: 0,
      targetScore: 50,
      gameStatus: '',
      message: '',
      hintIndex: -1
    })
    this.generateNumbers()
  },

  // 生成随机数字
  generateNumbers() {
    const numbers = []
    for (let i = 0; i < 16; i++) {
      numbers.push(Math.floor(Math.random() * 9) + 1)
    }
    this.setData({ numbers })
  },

  // 处理数字点击
  onNumberTap(e) {
    if (this.data.gameStatus !== '') return
    
    const index = e.currentTarget.dataset.index
    const selectedNumber = this.data.numbers[index]
    const newScore = this.data.score + selectedNumber
    
    // 更新数字
    const numbers = this.data.numbers
    numbers[index] = Math.floor(Math.random() * 9) + 1
    
    this.setData({
      score: newScore,
      numbers: numbers,
      hintIndex: -1
    })
    
    // 检查游戏状态
    this.checkGameStatus(newScore)
  },

  // 检查游戏状态
  checkGameStatus(score) {
    if (score === this.data.targetScore) {
      this.setData({
        gameStatus: 'win',
        message: '恭喜你赢了！点击重新开始再玩一次。'
      })
    } else if (score > this.data.targetScore) {
      this.setData({
        gameStatus: 'lose',
        message: '超过目标分数了！点击重新开始再试一次。'
      })
    }
  },

  // 重新开始游戏
  restartGame() {
    this.initGame()
  },

  // 显示提示
  showHint() {
    if (this.data.gameStatus !== '') return
    
    const needed = this.data.targetScore - this.data.score
    if (needed <= 0) return
    
    // 找到最接近所需分数的数字
    let closest = { index: -1, value: 0, diff: Infinity }
    
    this.data.numbers.forEach((number, index) => {
      const diff = Math.abs(number - needed)
      if (diff < closest.diff) {
        closest = { index, value: number, diff }
      }
    })
    
    if (closest.index !== -1) {
      this.setData({ hintIndex: closest.index })
      
      // 3秒后取消提示
      setTimeout(() => {
        this.setData({ hintIndex: -1 })
      }, 3000)
    }
  }
})